package com.zhdl.network.common_server;

import com.project.network.conf.LinkServerSocketBuild;
import com.project.network.entity.PortSocket;
import com.project.network.server.SerialSocketServer;
import com.zhdl.network.common_server.dto.CommonServerPacket;
import com.zhdl.network.strategy.common_server.impl.CommonServerSendServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

import static com.project.common.constant.Dic.HAND_MODBUS_RTU_ANALYSIS;


@Slf4j
@Component
public class CommonTcpServerSocketBuild extends LinkServerSocketBuild {

    @Resource
    private CommonServerSendServiceImpl commonServerSendServiceImpl;

    private SerialSocketServer buildServer(PortSocket portSocket) throws IOException {
        String protocols = portSocket.getProtocols();
        String serverIp = portSocket.getServerIp();
        String serverPort = portSocket.getServerPort();
        CommonTcpServerHandler handler = new CommonTcpServerHandler(serverIp, serverPort, protocols, message);
        CommonTcpServerListener listener = new CommonTcpServerListener(commonServerSendServiceImpl);
        CommonServerPacket packet = new CommonServerPacket();
        SerialSocketServer socket = new SerialSocketServer(handler, listener, packet, serverIp, serverPort);
        socket.openServerSocket(HAND_MODBUS_RTU_ANALYSIS, serverIp, Integer.parseInt(serverPort), 1000 * 60, handler, listener);
        return socket;
    }

    @Override
    protected SerialSocketServer buildSocketServer(PortSocket properties) throws IOException {
        //hand-modbus-rtu
        if (HAND_MODBUS_RTU_ANALYSIS.equals(properties.getProtocols())) {
            return buildServer(properties);
        }
        return null;
    }
}
